package com.zhiwang.planet.ui.my.withdraw

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.DiffUtil
import com.zhiwang.planet.R
import com.zhiwang.planet.databinding.ActivityWithDrawRecordBinding
import com.zhiwang.planet.di.component.DaggerUserComponent
import com.zhiwang.planet.di.module.AccountModule
import com.zhiwang.planet.di.module.AutoDisposeModule
import com.zhiwang.planet.mvp.v.WithDrawRecordView
import com.zhiwang.planet.mvvm.model.entity.main.WithDrawRecord
import com.zhiwang.planet.mvvm.model.entity.main.WithDrawRecordBody
import com.zhiwang.planet.mvvm.viewmodel.CommonListViewModel
import com.zhiwang.planet.ui.BaseFragment
import com.zhiwang.planet.ui.my.withdraw.WithDrawRecordFragment.RecordAdapter.VH
import com.zhiwang.planet.widget.SimpleDialogBuilder
import kotlinx.android.synthetic.main.activity_with_draw_record.*
import kotlinx.android.synthetic.main.item_withdraw_record2.view.*
import javax.inject.Inject

class WithDrawRecordFragment : BaseFragment(), WithDrawRecordView {
//
//    @Inject
//    lateinit var userPresenter: UserPresenter

    val diff = object : DiffUtil.ItemCallback<WithDrawRecord>() {

        override fun areItemsTheSame(oldItem: WithDrawRecord, newItem: WithDrawRecord) = oldItem == newItem


        override fun areContentsTheSame(oldItem: WithDrawRecord, newItem: WithDrawRecord) = areItemsTheSame(oldItem, newItem)

    }


    var recordAdapter = RecordAdapter(diff)


    @Inject
    lateinit var commonListViewModel: CommonListViewModel


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initInjection()
    }

    fun initInjection() {
        DaggerUserComponent.builder()
                .appComponent(getAppComponent())
                .accountModule(AccountModule(context as AppCompatActivity))
                .autoDisposeModule(AutoDisposeModule(this))
                .build()
                .inject(this)
//        userPresenter.withdrawRecordView = this
    }


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        val root = inflater.inflate(R.layout.activity_with_draw_record, container, false)
        val binding = DataBindingUtil.bind<ActivityWithDrawRecordBinding>(root)
//        setSupportActionBar(toolbar)
        binding?.commondListViewModel = commonListViewModel
        binding?.refreshProxy = ClickProxy()
        binding?.lifecycleOwner = viewLifecycleOwner
        return root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        init()
    }

    private fun init() {
        recyclerView.adapter = recordAdapter


        commonListViewModel.refreshState.observe(viewLifecycleOwner, Observer {
            commonListViewModel.refreshing.set(it)
        })
        commonListViewModel.loadMoreState.observe(viewLifecycleOwner, Observer {
            commonListViewModel.loadingMore.set(it)
        })

        commonListViewModel.err.observe(viewLifecycleOwner, Observer(this::onError))
        commonListViewModel.records.observe(viewLifecycleOwner, Observer {
            recordAdapter.submitList(it)
            commonListViewModel.emptyHint.set(recordAdapter.itemCount <= 0)
            smartRefresh.finishRefresh()
            smartRefresh.finishLoadMore()
        })

    }

    inner class ClickProxy {

        fun onRefresh() {

            recordAdapter.currentList?.dataSource?.invalidate()

        }

    }

    override fun onPageRefresh(it: WithDrawRecordBody) {
//        emptyView.visibility = if (it.data.isEmpty()) View.VISIBLE else View.GONE
////        recordAdapter.setDatas(it.data)
//        pageIndex = 1
//        smartRefresh.setEnableLoadMore(recordAdapter.itemCount < it.total)
//        smartRefresh.finishRefresh()
    }

    override fun onNextPageLoad(it: WithDrawRecordBody) {

    }


    inner class RecordAdapter constructor(differ: DiffUtil.ItemCallback<WithDrawRecord>) : PagedListAdapter<WithDrawRecord, VH>(differ) {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
            return VH(layoutInflater.inflate(R.layout.item_withdraw_record2, parent, false))
        }


        override fun onBindViewHolder(holder: VH, position: Int) {
            getItem(holder.adapterPosition)?.apply { holder.bind(this) }
        }


        val itemClickListener = View.OnClickListener {
            val position = recyclerView.getChildViewHolder(it).adapterPosition

            val item = getItem(position)!!
            val title = item.statusText
            val msg = item.failMsg
            showFailMsg(title, msg)
        }


        inner class VH(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView) {

            fun bind(data: WithDrawRecord) {

                itemView.withdraw_state.text = data.statusText
                itemView.withdraw_type.text = data.typeText
//                itemView.time.text = data.timeDesc
                itemView.date.text = data.dateDesc
                itemView.withdraw_amount.text = data.money
//                itemView.fl_center.headerVisible = adapterPosition != 0
                val color = ContextCompat.getColor(itemView.context,
                        if (data.status != 30) R.color.colorOrange else R.color.colorComplete)
                itemView.withdraw_state.setTextColor(color)
                itemView.setOnClickListener(itemClickListener)

            }
        }

    }

    private fun showFailMsg(title: String, msg: String) {

        if (msg.isNotEmpty()) {
            SimpleDialogBuilder()
                    .title(title)
                    .titleTextSizeSp(17f)
                    .titleTextColor(R.color.colorPrimary)
                    .buttonText("我知道了")
                    .contenxtTextSize(14f)
                    .buttonTextSizeSp(15f)
                    .content(msg)
                    .build(requireActivity())
                    .show()
        }
    }


}
